package com.elinkway.infinitemovies.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.elinkway.infinitemovies.bean.HomePageList;
import com.elinkway.infinitemovies.http.parser.HomePageParser;

import org.json.JSONObject;

/**
 * Created by biandi on 2017/6/26.
 */

public class ChannelContentDao extends BaseDao<HomePageList> {

    private static final String TABLE_NAME = "channel_content";
    private static final String PAGE = "page";
    private static final String JSON = "json";

    public ChannelContentDao(Context context) {
        super(context);
    }

    @Override
    public void delete(String pk) {

    }

    @Override
    public void delAll() {

    }
    public void saveJson(final String json,final String page) {
        doInBackground(new Runnable() {

            @Override
            public void run() {
                SQLiteDatabase db = safelyGetDataBase();
                db.execSQL(String.format("delete from %s where %s='%s'", TABLE_NAME, PAGE, page));
                Cursor cursor = db.rawQuery(String.format("Select * from %s;", TABLE_NAME), null);
                ContentValues values = new ContentValues();
                values.put(PAGE, page);
                values.put(JSON, json);
                db.insert(TABLE_NAME, null, values);
                safelyCloseDataBase();
                cursor.close();
            }
        });
    }

    public synchronized HomePageList getContentByPage(String page,String json) {
        HomePageList list = new HomePageList();
        if (!TextUtils.isEmpty(json)) {
            try {
                HomePageParser pageParser = new HomePageParser(page,false);
                list = pageParser.parse(new JSONObject(json));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return list;
    }

    public synchronized String getJsonByPage(String page) {
        String json = "";
        SQLiteDatabase db = safelyGetDataBase();
        Cursor cursor = db.rawQuery(String.format("select * from %s where %s='%s'", TABLE_NAME,PAGE,page), null);
        int index = cursor.getColumnIndex(JSON);
        if (cursor.getCount() != 0) {
            cursor.moveToFirst();
            json = cursor.getString(index);
        }
        safelyCloseDataBase();
        cursor.close();
        return json;
    }

    @Override
    public void save(HomePageList bean) {

    }


}
